/*
 * Copyright (c) 2021
 * User:魔金多商户商城
 * File:JwtAuthenticationTokenFilter.java
 * Date:2020/11/27 16:26:27
 */

package com.ruoyi.interceptor;


import com.ruoyi.common.utils.ThreadTask;
import com.ruoyi.system.domain.SysOperLog;
import com.ruoyi.system.mapper.SysOperLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * JWT登录授权过滤器
 * https://github.com/shenzhuan/mallplus on 2018/4/26.
 */
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Resource
    public SysOperLogMapper fopSystemOperationLogService;


    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws ServletException, IOException {
        long startTime, endTime;

        String requestType = ((HttpServletRequest) request).getMethod();
        SysOperLog sysLog = new SysOperLog();
        String fullUrl = ((HttpServletRequest) request).getRequestURL().toString();
        log.info(fullUrl);
        int startIntercept = fullUrl.replace("//", "a").indexOf("/") + 2;
        String interfaceName = fullUrl.substring(startIntercept, fullUrl.length());


        String requestIdKey = "requestId";
        startTime = System.currentTimeMillis();
        try {
            String requestId = UUID.randomUUID().toString().replace("-", "");
            MDC.put(requestIdKey, requestId);
            chain.doFilter(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            MDC.remove(requestIdKey);
        }

        endTime = System.currentTimeMillis();

        sysLog.setCreateTime(new Date());

        sysLog.setMethod(interfaceName);


        sysLog.setOperatorType((endTime - startTime));
        if (!"OPTIONS".equals(requestType) && !interfaceName.contains("webjars")
                && !interfaceName.contains("api-docs")) {
            sysLog.setBusinessType(999);
            ThreadTask.getInstance().addTask(() -> {
                //   fopSystemOperationLogService.insertOperlog(sysLog);
            });
            log.info("interfaceName:{},time:{},", interfaceName, sysLog.getOperatorType());
        }
    }


}
